﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LockTime
{
    public partial class Form1 : Form
    {
        DateTime now = new DateTime();
        Process[] myprocess = null;
        string s = "";  //存放锁定程序路径
        public Form1()
        {
            InitializeComponent();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            //退出窗体
            SaveFile();
            Close();
        }
        /// <summary>
        /// 将listview内容保存为文件
        /// </summary>
        private void SaveFile()
        {
            try
            {
                //遍历listview，存进文件
                string str = "";
                foreach (ListViewItem lvvi in FilelistView.Items)
                {
                    str += (lvvi.Text + "\t" + lvvi.SubItems[1].Text+"\n");
                }
                FileCtl.SaveFile(str);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        private void btnGetAdmin_Click(object sender, EventArgs e)
        {
            //获取管理员权限
            ProcessStartInfo processInfo = new ProcessStartInfo();
            processInfo.Verb = "runas";
            processInfo.FileName = Assembly.GetExecutingAssembly().Location;

            try
            {
                //保存文件，进程重启
                SaveFile();
                Process.Start(processInfo);
            }
            catch (Win32Exception ex)
            {
                // 忽略错误 1223: 用户取消操作
                if (ex.NativeErrorCode == 1223)
                {
                    return;
                }

                throw;
            }

            Application.Exit();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            //添加要锁定的程序
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if (openFileDialog1.FileName != string.Empty)
                {
                    ProtextBox.Text = openFileDialog1.FileName;
                    now = DateTime.Now;
                    timelabel.Text = "当前待锁定的时间: " + now;
                    ListViewItem lv = new ListViewItem(now.ToString());
                    lv.SubItems.Add(ProtextBox.Text);
                    FilelistView.Items.Add(lv);

                    SaveFile();

                }


            }
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            try
            {
                //移除一个项目
                FilelistView.Items.Remove(FilelistView.SelectedItems[0]);
            }
            catch (Exception ex)
            {
                MessageBox.Show("请选中一个项目！" + "\n" + ex.ToString());
            }
            finally
            {
                SaveFile();
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            //清空列表
            FilelistView.Items.Clear();
            SaveFile();
        }

        private void brnStart_Click(object sender, EventArgs e)
        {
            if (ProtextBox.Text == string.Empty)
            {
                MessageBox.Show("请选择一个待锁定的项目！");
            }
            else
            {
                try
                {
                    //布局
                    Hidepanel.Visible = true;
                    Showlabel.Visible = true;
                    SaveFile();

                    btnStart.Enabled = false;
                    btnStart.BZBackColor = Color.Gray;
                    btnGetAdmin.Enabled = false;
                    btnGetAdmin.BZBackColor = Color.Gray;

                    btnClose.Enabled = false;
                    btnClose.BZBackColor = Color.Gray;
                    //运行列表里待锁定的程序
                    s = ProtextBox.Text.Replace("\r", string.Empty).Replace("\n", string.Empty).Trim();
                    Process.Start(s);
                    timer1.Enabled = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("发生错误：" + ex.ToString());
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                //布局
                timer1.Enabled = false;
                Hidepanel.Visible = false;
                Hidepanel.Width = ClientRectangle.Width;
                Hidepanel.Height = ClientRectangle.Height;
                Hidepanel.Dock = DockStyle.Fill;
                Hidepanel.Top = 0;
                Hidepanel.Left = 0;
                Showlabel.Visible = false;
                Showlabel.Text = "锁定中……" + "\n" + "当你关闭被锁定的程序" + "\n" + "本程序将自动退出……" + "\n" + "如果你正连着网络" + "\n" + "会为你自动恢复正确时间";
                //读取INI文件填入listview
                ListViewItem lvi = null;
                string timestring;
                string[] temp, temp1;
                timestring = FileCtl.LoadFile();
                if(timestring!=string.Empty)
                {
                    temp = timestring.Split('\n');
                    foreach (var it in temp)
                    {
                        if(it!=string.Empty)
                        {
                            temp1 = it.Split('\t');
                            lvi = new ListViewItem(temp1[0]);
                            lvi.SubItems.Add(temp1[1]);
                            FilelistView.Items.Add(lvi);
                        }
                        
                    }
                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show("初始化错误!" + ex.ToString());
            }
        }

        private void FilelistView_Click(object sender, EventArgs e)
        {
            //更新textbox里的信息显示
            now = Convert.ToDateTime(FilelistView.SelectedItems[0].Text);
            timelabel.Text = "当前待锁定的时间: " + FilelistView.SelectedItems[0].Text;
            ProtextBox.Text = FilelistView.SelectedItems[0].SubItems[1].Text;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            ///锁定时间
            DateTime t = now;
            timelabel.Text = "锁定时间为: " + t;
            SYSTEMTIME st = new SYSTEMTIME();
            st=SystemTime.FromDateTime(t);
            SystemTime.SetLocalTime(ref st);

            ///监测打开的程序状态
            string[] sData = s.Split('\\');
            string[] sData1 = sData[sData.Length - 1].Split('.');
            myprocess = Process.GetProcessesByName(sData1[0]);
            if (myprocess.Length == 0)
            {
                DateTime dt = SystemTime.GetNetDateTime();
                if (dt != null)
                {
                    st = SystemTime.FromDateTime(dt);
                    SystemTime.SetLocalTime(ref st);
                }

                this.Close();
            }
        }
    }
}